package com.hendraanggrian.appcompat.widget;

import com.hendraanggrian.appcompat.socialview.commons.ResourceTable;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.app.Context;

/**
 * Default adapter for displaying hashtag in {@link}.
 * Note that this adapter is completely optional, any adapter extending
 * {@link ArrayProvider} can be attached to {@link}.
 */
public class HashtagArrayAdapter<T extends Hashtagable> extends SocialArrayAdapter<T> {
    public HashtagArrayAdapter(Context context) {
        super(context, ResourceTable.Layout_socialview_layout_hashtag_ohos);
    }

    @Override
    @SuppressWarnings("unchecked")
    public Component getComponent(int position, Component convertView, ComponentContainer parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutScatter.getInstance(getContext())
                    .parse(ResourceTable.Layout_socialview_layout_hashtag_ohos, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final T item = getItem(position);
        if (item != null) {
            holder.hashtagView.setText(item.getId() + "");

            if (item.getCount() > 0) {
                holder.countView.setVisibility(Component.VISIBLE);
                final int count = item.getCount();
                holder.countView.setText(count + " posts");
            } else {
                holder.countView.setVisibility(Component.HIDE);
            }
        }
        return convertView;
    }

    private static class ViewHolder {
        private final Text hashtagView;
        private final Text countView;

        ViewHolder(Component itemView) {
            hashtagView = (Text) itemView.findComponentById(ResourceTable.Id_socialview_hashtag);
            countView = (Text) itemView.findComponentById(ResourceTable.Id_socialview_hashtag_count);
        }
    }
}
